package org.fujie.plugin.cloud.face.aliyun.convert;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.fujie.plugin.cloud.core.model.RecognizedIdCardScanRes;

import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Optional;

/**
 * @author slm
 * @description
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AliIdCardConvert {

    public static RecognizedIdCardScanRes ofFront(JsonNode node) {

        RecognizedIdCardScanRes recognizedIdCardScanRes = new RecognizedIdCardScanRes();
        recognizedIdCardScanRes.setCertNo(node.get("idNumber").asText());
        recognizedIdCardScanRes.setCertName(node.get("name").asText());
        recognizedIdCardScanRes.setSex(node.get("sex").asText());
        recognizedIdCardScanRes.setEthnicity(node.get("ethnicity").asText());
        recognizedIdCardScanRes.setBirthDate(node.get("birthDate").asText());
        recognizedIdCardScanRes.setAddress(node.get("address").asText());
        return recognizedIdCardScanRes;
    }

    public static RecognizedIdCardScanRes ofBack(JsonNode node) {

        RecognizedIdCardScanRes recognizedIdCardScanRes = new RecognizedIdCardScanRes();
        recognizedIdCardScanRes.setIssueAuthority(node.get("issueAuthority").asText());
        recognizedIdCardScanRes.setValidPeriod(node.get("validPeriod").asText());

        String validPeriod = node.get("validPeriod").asText();

        List<String> dateList = StrUtil.splitTrim(validPeriod, "-")
                .stream()
                .map(s -> {
                    if (CharSequenceUtil.equalsIgnoreCase("长期", s)) {
                        return Optional.of(s);
                    } else {
                        try {
                            String formattedDate = LocalDateTimeUtil.format(LocalDateTimeUtil.parse(s, "yyyy.mm.dd"), DatePattern.PURE_DATE_PATTERN);
                            return Optional.of(formattedDate);
                        } catch (DateTimeParseException e) {
                            return Optional.<String>empty();
                        }
                    }
                })
                .flatMap(Optional::stream)
                .toList();

        if (dateList.size() == 2) {
            recognizedIdCardScanRes.setStartDate(dateList.get(0));
            recognizedIdCardScanRes.setEndDate(dateList.get(1));
        }
        return recognizedIdCardScanRes;
    }

}
